import React from 'react';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DownOutlined
} from '@ant-design/icons';
import { Layout,theme,Dropdown,Space } from 'antd';
import { useSelector,useDispatch } from 'react-redux';
import {setCollapsed} from '@/store/modules/app'
import AppBreadcrumb from './AppBreadcrumb'
import {useLocation, useNavigate} from 'react-router-dom'
import store from 'store2'
import {changeLoginState} from '@/store/modules/admin'
const { Header } = Layout;
const items = [
  {
    label: '设置',
    key: '/setting',
  },
  {
    label: '退出',
    key: '/logout',
  },
];

export default function AppHeader() {
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  const dispatch = useDispatch()
  const collapsed = useSelector(state=>state.app.collapsed)
  const adminname = useSelector(state=>state.admin.adminname)
  const navigate = useNavigate()
  const { pathname } = useLocation()
  const onClick = ({ key }) => {
    if(key === '/logout'){
      store.remove('users')
      dispatch(changeLoginState(false))  // 同步redux状态，将其变成false
      navigate('/login?redirect='+pathname)
    }else{
      navigate(key)
    }
  };
  return (
    <Header
      style={{
        padding: 0,
        background: colorBgContainer,
        display:'flex'
      }}
    >
      {collapsed ? <MenuUnfoldOutlined className='trigger' onClick={()=>dispatch(setCollapsed(!collapsed))} /> 
                 : <MenuFoldOutlined className='trigger' onClick={()=>dispatch(setCollapsed(!collapsed))} />}
      <AppBreadcrumb/>
      <div style={{position:'absolute',right:'14px'}}>
        <Dropdown
          menu={{
            items,
            onClick,
          }}
          >
          <span onClick={(e) => e.preventDefault()}>
            <Space>
              {adminname}
              <DownOutlined />
            </Space>
          </span>
        </Dropdown>
      </div>
    </Header>
  )
}
